<
<template>
  <el-row>
    <el-col :span="8"></el-col>
    <el-col :span="8">
      <div style="margin-top: 20vh">
        <el-row>
          <el-col :span="4">用户：</el-col>
          <el-col :span="20">
            <el-input v-model="username" placeholder="请输入用户名"></el-input>
          </el-col>
        </el-row>
        <el-row class="mt-2">
          <el-col :span="4">密码：</el-col>
          <el-col :span="20">
            <el-input v-model="password" placeholder="请输入密码" type="password"></el-input>
          </el-col>
        </el-row>
        <el-row class="mt-2">
          <el-col :span="4"></el-col>
          <el-col :span="20">
            <el-space>
              <el-button type="primary" @click="submitLogin">登录</el-button>
              <el-button @click="resetForm">重置</el-button>
              <el-button type="primary" @click="submitRegister">注册</el-button>
            </el-space>
          </el-col>
        </el-row>
      </div>
    </el-col>
    <el-col :span="8"></el-col>
  </el-row>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { userLogin, userRegister } from '../../http/user'
defineOptions({ name: 'Login' })

const router = useRouter()

const username = ref('')
const password = ref('')

const resetForm = () => {
  username.value = ''
  password.value = ''
}

const submitRegister = () => {
  const params = {
    username: username.value,
    password: password.value,
  }
  userRegister(params).then((res) => {
    if (res.data.code !== 200) {
      alert(res.data.message)
      return
    }
  })
}
const submitLogin = () => {
  const params = {
    username: username.value,
    password: password.value,
  }
  userLogin(params).then((res) => {
    if (res.data.code !== 200) {
      alert(res.data.message)
      return
    }
    let token = res.data.data
    window.localStorage.setItem('username', username.value)
    window.localStorage.setItem('cq-token', token)
    router.push({
      name: 'Home',
    })
  })
}

onMounted(() => {
  if (localStorage.getItem('cq-token')) {
    router.push({
      name: 'Home',
    })
  }
})
</script>
